/* eslint-disable no-undef */
/* eslint-disable space-before-function-paren */
import { useEffect, useState } from 'react';
import { useLocalStorageState, usePersistFn, useRequest } from 'ahooks';
import { appChannelReport, getTrench } from '@/service/live';
import { getRequestUrlParams, getDeviceId } from './utils';

/**
 * 渠道来路
 * @param defaultValue
 */
export const useChannelOrigin = (defaultValue) => useLocalStorageState('x-channel-origin', defaultValue);
/**
 * OpenInstall SDK
 * @returns {{instance: unknown, wakeupOrInstall: (function(): *), schemeWakeup: (function(): *)}}
 */
export const useOpenInstall = () => {
  const [instance, setInstance] = useState(null);
  useEffect(() => {
    const { OpenInstall } = global;
    if (OpenInstall) {
      // openinstall.js中提供的工具函数，解析url中的所有查询参数
      const insData = OpenInstall.parseUrlParams();
      if (!insData?.channelCode) {
        // 无渠道码 直接调用open
        const ins = new OpenInstall({
          /* appKey必选参数，openinstall平台为每个应用分配的ID */
          appKey: process.env.OPEN_INSTALL_APP_KEY,
          /* 自定义遮罩的html */
          // mask:function(){
          //  return "<div id='_shadow' style='position:fixed;left:0;top:0;background:rgba(0,255,0,0.5);filter:alpha(opacity=50);width:100%;height:100%;z-index:10000;'></div>"
          // },
          /* OpenInstall初始化完成的回调函数，可选 */
          onready () {
            /* 在app已安装的情况尝试拉起app */
            ins.schemeWakeup();

            setInstance(ins);
          },
        }, insData);
      }
    }
  }, []);
  // OpenInstall渠道判断
  // eslint-disable-next-line no-undef
  const data = OpenInstall.parseUrlParams();
  const { loading: openLoading } = useRequest(() => getTrench(data?.channelCode || ''), {
    ready: !!data?.channelCode,
    defaultLoading: false,
    // eslint-disable-next-line space-before-function-paren
    onSuccess (res) {
      let url = window.location.origin + window.location.pathname;
      // eslint-disable-next-line no-undef
      if (res === 1) {
        // 清空渠道码,渠道码不正常
        window.localStorage.setItem('x-channel-origin', '');
        if (data?.agentId) {
          url += `?agentId=${data.agentId}`;
        }
        window.location.href = url;
      } else {
        // eslint-disable-next-line no-new
        // eslint-disable-next-line no-undef
        // eslint-disable-next-line no-new
        const ins = new OpenInstall({
          /* appKey必选参数，openinstall平台为每个应用分配的ID */
          appKey: process.env.OPEN_INSTALL_APP_KEY,
          onready () {
            /* 在app已安装的情况尝试拉起app */
            ins.schemeWakeup();
            setInstance(ins);
          },
        }, data);
      }
    },
  });

  // 在app已安装的情况尝试拉起app
  const schemeWakeupHandle = usePersistFn(() => instance?.schemeWakeup());

  // 用户点击某个按钮时，安装app
  const wakeupOrInstallHandle = usePersistFn(() => instance?.wakeupOrInstall());

  return {
    instance,
    schemeWakeup: schemeWakeupHandle,
    wakeupOrInstall: wakeupOrInstallHandle,
    openLoading,
  };
};
/**
 * 平台判断
 * @returns {{isAndroid: boolean, isIos: boolean}}
 */
export const usePlatform = () => {
  const u = navigator.userAgent;
  // Android
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
  // ios
  const isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

  const platform = isIos ? 'ios' : (isAndroid ? 'android' : '');

  return {
    isAndroid,
    isIos,
    platform,
  };
};

/**
 * 数据上报
 */
export const useAppChannelReport = () => {
  const [channelOrigin, setChannelOrigin] = useChannelOrigin();

  const { run: runAppChannelReport } = useRequest(
    appChannelReport,
    {
      manual: true,
    },
  );

  const onDownloadReportHandle = usePersistFn((code) => {
    if (!channelOrigin) return;
    if (channelOrigin.name !== 'channel') return;

    return runAppChannelReport({
      actionCode: code,
      actionName: code,
      channelUrl: channelOrigin.value,
      deviceid: getDeviceId(),
      platform: 'H5',
      user_agent: navigator.userAgent,
    });
  });

  const setChannelUrlHandle = usePersistFn((channelUrlVal) => {
    if (channelUrlVal) {
      if (typeof channelUrlVal === 'string') {
        setChannelOrigin({ name: 'channel', value: channelUrlVal });
      } else {
        setChannelOrigin({ name: channelUrlVal.name, value: channelUrlVal.value });
      }
    } else {
      const { protocol, origin, href } = global.location;
      const { channel, channelCode } = getRequestUrlParams(href);
      if (channel) {
        setChannelOrigin({ name: 'channel', value: channel });
      } else if (channelCode) {
        setChannelOrigin({ name: 'channelCode', value: channelCode });
      } else {
        const { referrer } = document;
        if (referrer && referrer.replace(/^(http?s):/, protocol).indexOf(origin) === -1) {
          setChannelOrigin({ name: 'channel', value: referrer });
        }
      }
    }
  });

  return [onDownloadReportHandle, setChannelUrlHandle];
};
